<script setup>
import {ref} from 'vue';

// 导入区域相关api
import {getOpenedTreeApi, getProvinceListApi, getCityListApi, openCityApi, closeCityApi} from '@/service/zone.js';

const provinceList = ref([]);
const cityList = ref([]);
const form = ref({
  province_id: '',
  city_id: ''
});

// 充值form
const restForm = () => {
  form.value.province_id = '';
  form.value.city_id = '';
};

// 获取省份列表
const fetchProvinceList = () => {
  getProvinceListApi().then(res => {
    provinceList.value = res.data.list;
  });
};

// 获取城市列表
const fetchCityList = () => {
  getCityListApi({id: form.value.province_id}).then(res => {
    cityList.value = res.data.list;
  });
};


// 获取已开通区域
const openedTree = ref([]);
const fetchOpenedTree = () => {
  getOpenedTreeApi().then(res => {
    openedTree.value = res.data.tree;
  });
};

// 开通区域
const doOpenCity = () => {
  openCityApi({province_id: form.value.province_id, city_id: form.value.city_id}).then(res => {
    fetchOpenedTree();
    restForm();
  });
};

// 关闭区域
const doCloseCity = (row) => {
  closeCityApi({id: row.id}).then(res => {
    fetchOpenedTree();
  });
};

// 默认加载
onMounted(() => {
  fetchProvinceList();
  fetchOpenedTree();
});

</script>

<template>

  <el-main>
    <div class="toolbar">
      <el-select v-model="form.province_id" placeholder="请选择省份" style="width: 200px;" filterable clearable
                 @change="fetchCityList">
        <el-option
            v-for="item in provinceList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-select v-model="form.city_id" placeholder="请选择城市" style="width: 200px;" clearable
                 v-if="form.province_id > 0">
        <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-button type="primary" @click="doOpenCity">开通区域</el-button>
      <el-button type="danger" @click="restForm">重置</el-button>

    </div>

    <el-table :data="openedTree" row-key="id" border>
      <el-table-column prop="name" label="区域名称"/>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" @click="doCloseCity(row)">关闭</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-main>
</template>

<style scoped>

</style>
